/*
  testbe.js
  用于测试的简单聊天室后端程序
*/

const Room = require('./room.js')

let players

const room = new Room({
  port: 7788,
  maxPlayers: 10,
  minPlayers: 1
}, async ps => {
  players = ps
  while (1) {
    let msg
    try {
      msg = await room.recv()
    } catch (e) {
      const ind = players.indexOf(e)
      if (ind >= 0) {
        players.splice(ind, 1)
      }
      if (players.length <= 0) {
        break
      }
      continue
    }
    for (const p of players) {
      if (p == msg.player) {
        room.sendTo(p, `You say: ${msg.message}`)
      } else {
        room.sendTo(p, `Player${msg.player} says: ${msg.message}`)
      }
    }
  }
}, p => players.push(p))
